package com.nishop.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;	

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;

import com.google.common.base.Splitter;

public class LoginFilter implements Filter{
	
	private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	
	private List<String> excludedUrls;
	
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	excludedUrls = Splitter.on(",").splitToList(filterConfig.getInitParameter("excludedUrls"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    	boolean match = false;
    	String url = ((HttpServletRequest) servletRequest).getRequestURI();
    	logger.info("url filter:"+url);
    	AntPathMatcher matcher = new AntPathMatcher(); 
    	for (String excludedUrl : excludedUrls) {
			if(matcher.match(excludedUrl, url)){
				match = true;
				break;
			}
		}
    	if(match){
    		filterChain.doFilter(servletRequest, servletResponse);
    	}else{
    		 ((HttpServletResponse)servletResponse).sendRedirect(servletRequest.getServletContext().getContextPath()+"/login");
    	}
    }

    @Override
    public void destroy() {

    }
}
